# -*- coding: UTF-8 -*-
import json
import re

from flask import Blueprint
from flask import request

import conf
import log_helper
import lte_controller
import power_helper
import tcp_server
from utils import ip_utils
from web.decorator import api_call

logger = log_helper.init_logging('swj')
m_web = Blueprint("m_api", __name__)


@m_web.route("/receive", methods=['POST', 'GET'])
@api_call
def call():
    request_text = request.get_data(as_text=True)
    logger.info(request_text)
    if not request_text:
        return {"_status": 1, "_msg": "接受参数为空"}
    request_cmd = json.loads(request_text)
    cmd_type = request_cmd.get('cmdType')
    if cmd_type is None:
        return {"_status": 1, "_msg": "cmdType错误"}
    if cmd_type == 'btsQuery':
        return bts_query(request_cmd)
    if cmd_type == 'Sniffer':
        return start_sniffer(request_cmd)
    if cmd_type == 'redirect':
        return do_redirect(request_cmd)
    if cmd_type == 'lte':
        return set_lte(request_cmd)
    if cmd_type == 'netmode':
        return set_netmode(request_cmd)
    if cmd_type == 'mode':
        return set_mode(request_cmd)
    if cmd_type == 'setBts':
        return set_bts(request_cmd)
    if cmd_type == 'power':
        return set_power(request_cmd)
    if cmd_type == 'device':
        return set_device(request_cmd)
    if cmd_type == 'auth':
        return tcp_server.rec_auth_info(request_cmd)
    # 五元鉴权authims 改为 auth
    if cmd_type == 'ims':
        return tcp_server.rec_auth_ims(request_cmd)
    # 黑白名单
    if cmd_type == 'setList':
        return set_list(request_cmd)
    if cmd_type == 'queryList':
        return query_list(request_cmd)
    if cmd_type == 'smsSend':
        params = request_cmd['params']
        sms_type = str(params.get('type', '1'))
        # 短信发送
        if sms_type == '1':
            return tcp_server.recive_sms_info(request_cmd)
        else:  # 彩信发送
            return tcp_server.receive_sms_media_info(request_cmd)
    if cmd_type == 'location':
        return a_location(request_cmd)
    # 音视频下载
    if cmd_type == 'downloadReq':
        return lte_controller.download_tone(request_cmd)
    # 生成彩信文件
    if cmd_type == 'mmsFile':
        return lte_controller.generate_sms_media_file(request_cmd)
    # 彩信地址
    if cmd_type == 'mmsAddr':
        return lte_controller.set_mms_addr(request_cmd)
    # 下发语音
    if cmd_type == 'callRev':
        tcp_server.recive_call_info(request_cmd)
        return {}
    # sip setting
    if cmd_type == 'sipAccount':
        return set_sip_account(request_cmd)
    if cmd_type == 'querySip':
        return query_sip_account(request_cmd)
    if cmd_type == 'shutdown':
        lte_controller.shutdown()
        return {}
    # ip v4/v6 设置
    if cmd_type == 'ipType':
        return set_ip_type(request_cmd)
    return {"_status": 1, "_msg": "cmdType错误"}


def a_location(req_data):
    turnon = req_data.get('params', {}).get('turnOn', 0)
    # 1 open 2 close
    if int(turnon) in (1, 2):
        lte_controller.set_location(int(turnon))
    return {}


def bts_query(req_data):
    band = power_helper.get_band()
    rf_param = lte_controller.get_rf_param()
    ip_mode = lte_controller.query_ip_mode()
    # xml_info = lte_controller.get_bts_info()
    # plmnid = lte_controller.get_plmn_id()
    # 非debug模式
    device_info = ip_utils.get_device_info()
    device_type = device_info.split('-')[1]
    bandinfo = int(device_type[1:])
    power = rf_param['txPwr']
    if not conf.power_debug:
        power = power_helper.get_power()
    return {'type': 1,
            'bandinfo': int(band),
            'band': bandinfo,
            'earfcn': int(rf_param['FCN']),
            'tac': int(rf_param['LAC-TAC']),
            'pci': int(rf_param['CPI-PSC-BSIC']),
            'cellId': int(rf_param['cellID']),  # cellid -> cellId
            'plmn': int(str(rf_param['MCC']) + str(rf_param['MNC'])),
            'power': int(power),
            'iptype': ip_mode
            }


def set_ip_type(req_data):
    """
    ip设置  mode：0：ipv4 1：ipv6
    """
    ip_mode = str(req_data.get('params', {}).get('mode', '0'))
    if ip_mode not in ('0', '1'):
        return {'_status': 1, '_msg': 'params.mode 值错误'}
    lte_controller.set_ip_mode(ip_mode)
    return {}


def start_sniffer(req_data):
    ret = lte_controller.start_sniffer()
    if ret != 'SUCCESS':
        return {'_status': 1, '_msg': ret}
    return {}


def do_redirect(req_data):
    arcfn = req_data.get('params', {}).get('arcfn', '')
    mode = req_data.get('params', {}).get('mode', '3')
    lte_controller.set_arcfn(arcfn)
    lte_controller.set_mode(mode)
    return {}


def is_valid_ip(ip):
    if re.match(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", ip):
        return True
    else:
        return False


def set_lte(req_data):
    primaryDNS = req_data.get('params', {}).get('primaryDns')
    secondaryDNS = req_data.get('params', {}).get('secondaryDns')
    packetGwIP = req_data.get('params', {}).get('packetIp')
    if not is_valid_ip(primaryDNS):
        return {'_status': 10, '_msg': 'PrimaryDNS is invalid'}
    if not is_valid_ip(secondaryDNS):
        return {'_status': 10, '_msg': 'secondaryDNS is invalid'}
    if not is_valid_ip(packetGwIP):
        return {'_status': 10, '_msg': 'packetIP is invalid'}
    lte_controller.set_lte_addr(primaryDNS, secondaryDNS, packetGwIP)
    return {}


def set_netmode(req_data):
    mode = req_data.get('params', {}).get('mode')
    response = lte_controller.set_netmode(str(mode))
    if response != '':
        return {'_msg': response}
    return {}


def set_mode(req_data):
    mode = req_data['params']['mode']
    if mode in (1, 2, 3):
        lte_controller.set_mode_new(mode)
    return {}


def set_bts(req_data):
    lte_controller.set_bts_info(req_data.get('params', {}))
    return {}


def set_power(req_data):
    power = req_data.get('params', {}).get('power', 1)
    if int(power) not in (1, 2, 3, 4, 5):
        return {'_status': 10, '_msg': 'power value must between 1-5'}
    if not conf.power_debug:
        msg = 'set power success'
        if not power_helper.set_power_value(power):
            msg = 'set power fail'
    else:
        msg = lte_controller.set_power(power)
    if not msg:
        msg = 'set power success'
    return {'_msg': msg}


def set_device(req_data):
    setbts = req_data.get('params', {}).get('setbts', 1)
    msg = lte_controller.set_device(str(setbts))
    return {"_msg": msg}


def set_list(req_data):
    # 默认黑名单
    list_mode = req_data.get('params', {}).get('listmode', '1')
    operation = req_data.get('params', {}).get('operation')
    listinfo = req_data.get('params', {}).get('listinfo')
    voice_phone = req_data.get('params', {}).get('voice_phone')
    new_list_info = []
    for item in listinfo:
        new_list_info.append(str(item))
    lte_controller.set_white_black(str(list_mode), int(operation), new_list_info, voice_phone)
    return {}


def query_list(req_data):
    return lte_controller.query_black_white()


def set_sip_account(req_data):
    return lte_controller.set_sip_account(req_data)


def query_sip_account(req_data):
    return lte_controller.query_sip_account()
